//
//  TextFieldContainerView.swift
//  SCA
//
//  Created by tjun on 2025/9/1.
//

import UIKit
import SnapKit

@objc public protocol LabeledTextFieldDelegate: NSObjectProtocol {
    @objc optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
    @objc optional func textFieldDidBeginEditing(_ textField: UITextField)
    @objc optional func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
    @objc optional func textFieldDidEndEditing(_ textField: UITextField)
    @objc optional func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason)
    @objc optional func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    @objc optional func textFieldDidChangeSelection(_ textField: UITextField)
    @objc optional func textFieldShouldClear(_ textField: UITextField) -> Bool
    @objc optional func textFieldShouldReturn(_ textField: UITextField) -> Bool
}

class LabeledTextField: UIView {
    
    weak var delegate: LabeledTextFieldDelegate?

    let titleLabel = UILabel(font: UIFontMediumMake(15), textColor: Assets.Color.labeledTextFieldTitle)
    let tipLabel = UILabel(font: UIFontMake(12), textColor: Assets.Color.labeledTextFieldTip)

    let textField = UITextField()
    let contentView = UIView()
    
    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    
    var titleAttributedText: NSAttributedString? {
        didSet {
            titleLabel.attributedText = titleAttributedText
        }
    }

    var textFieldCornerRadius: CGFloat = 15 {
        didSet {
            contentView.layer.cornerRadius = textFieldCornerRadius
        }
    }
    
    private let tip: String?
    
    init(tip: String? = nil) {
        self.tip = tip
        tipLabel.text = tip
        super.init(frame: .zero)
        
        setupUI()
        setupConstraints()
        setupTextField()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI 布局
    private func setupUI() {
        
        contentView.layer.cornerRadius = 15
        contentView.layer.borderWidth = 1
        contentView.backgroundColor = Assets.Color.hex2E3036
        contentView.layer.borderColor = UIColor.clear.cgColor

        textField.borderStyle = .none
        textField.textColor = Assets.Color.labeledTextFieldInput
        textField.font = UIFont.systemFont(ofSize: 16)
        textField.returnKeyType = .done
        textField.clearButtonMode = .whileEditing
        textField.keyboardAppearance = ThemeManager.shared.currentStyle == .dark ? .dark : .light
        
        addSubview(titleLabel)
        addSubview(contentView)
        addSubview(tipLabel)
        contentView.addSubview(textField)
    }
    
    private func setupConstraints() {
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(4)
            make.left.equalToSuperview().offset(2)
        }
        
        textField.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(8)
        }
        
        if tip == nil {
            contentView.snp.makeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(6)
                make.height.equalTo(44)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview()
            }
                
        } else {
            contentView.snp.makeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(6)
                make.height.equalTo(44)
                make.left.right.equalToSuperview()
            }
            
            tipLabel.text = tip
            tipLabel.numberOfLines = 0
            tipLabel.snp.makeConstraints { make in
                make.top.equalTo(contentView.snp.bottom).offset(6)
                make.left.right.equalToSuperview().inset(2)
                make.bottom.equalToSuperview()
            }
        }
    
    }
    
    private func setupTextField() {
        textField.delegate = self
    }

    // MARK: - 动画方法
    private func animateBorderColor(toColor: CGColor) {
        let animation = CABasicAnimation(keyPath: "borderColor")
        animation.fromValue = contentView.layer.borderColor
        animation.toValue = toColor
        animation.duration = 0.25  // 动画时长
        animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        contentView.layer.add(animation, forKey: "borderColor")
        contentView.layer.borderColor = toColor
    }
    
    
}


extension LabeledTextField: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 通知外部代理
        if let result = delegate?.textFieldShouldReturn?(textField) {
            return result
        }
        // 如果外部没有实现，就默认处理
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        animateBorderColor(toColor: Assets.Color.hex2078D5.cgColor)
        
        delegate?.textFieldDidBeginEditing?(textField)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        animateBorderColor(toColor: UIColor.clear.cgColor)
        
        delegate?.textFieldDidEndEditing?(textField)
    }
 
    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        return delegate?.textField?(textField,
                                           shouldChangeCharactersIn: range,
                                           replacementString: string) ?? true
    }
}
